package yabandpay

import (
    "errors"
	"strings"
	"encoding/json"
	"thirdpaysdk/utils/mapstruct"
	//"github.com/astaxie/beego"
)

type NotifyData struct {
	OrderId       string  `json:"order_id"`
	TradeId       string  `json:"trade_id"`
	TransactionId string  `json:"transaction_id"`
	Description   string  `json:"description"`
	Amount        string  `json:"amount"`
	Currency      string  `json:"currency"`
	NonceStr      string  `json:"nonce_string"` 
	CreateDate    string  `json:"createDate"`
	State         string  `json:"state"`
}

type YaNotifyMsg struct {
	Sign       string      `json:"sign"`
	NotifyData NotifyData  `json:"data"`
}

type YaNotifySignMsg struct {
	Sign       string          `json:"sign"`
	NotifyData json.RawMessage `json:"data"`
}

func ParseYabandNotify(message []byte, response *YaNotifyMsg) error{
	err := json.Unmarshal(message, &response)
	if err != nil {
		return err
	}
	return nil
}

func YabandNotify(message []byte, appKey string,response YaNotifyMsg) (map[string]interface{}, error){
	var signResponse YaNotifySignMsg
	err := json.Unmarshal(message, &signResponse)
	if err != nil {
	   return map[string]interface{}{}, err
	}
	secreCode := appKey
	calcSign := ComputeHmac256(string(signResponse.NotifyData), secreCode)
	//beego.Debug("calcSign:", calcSign)
	//beego.Debug("signResponse.Sign:", signResponse.Sign)
	result := strings.EqualFold(signResponse.Sign, calcSign)
	if !result {
		returnMsg := "sign is invalid"
		return map[string]interface{}{}, errors.New(returnMsg)
	}
	rspMap :=  mapstruct.Struct2Map(response.NotifyData, "json")
	return rspMap, nil
}
